package com.fanfan.controller;

import com.fanfan.enums.AppHttpCodeEnum;
import com.fanfan.exception.SystemException;
import com.fanfan.pojo.LoginUser;
import com.fanfan.pojo.Menu;
import com.fanfan.pojo.User;
import com.fanfan.pojo.domain.ResponseResult;
import com.fanfan.pojo.vo.AdminUserInfoVo;
import com.fanfan.pojo.vo.RoutersVo;
import com.fanfan.pojo.vo.UserInfoVo;
import com.fanfan.service.LoginService;
import com.fanfan.service.MenuService;
import com.fanfan.service.RoleService;
import com.fanfan.utils.BeanCopyUtils;
import com.fanfan.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        if(!StringUtils.hasText(user.getUserName())){
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }
    @GetMapping("getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
        //token获取用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        User user= loginUser.getUser();
        //用id获取perms(List<String>)
        System.out.println(user.getId());
        List<String> perms=menuService.selectPermsByUserId(user.getId());
        //用id获取roleKeys(List<String>)
        List<String> roleKeys=roleService.selectRoleKeyByUserId(user.getId());
        //将用户转化为UserInfoVo
        UserInfoVo userInfoVo= BeanCopyUtils.copyOne(user,UserInfoVo.class);
        //用AdminUserInfoVo对象封装data信息
        return ResponseResult.okResult(new AdminUserInfoVo(perms,roleKeys,userInfoVo));
    }
    @GetMapping("getRouters")
    public ResponseResult<RoutersVo> getRouters(){
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RoutersVo(menus));
    }
    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

}